package com.web.daonila.service.bussiness;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.web.daonila.message.resp.Article;
import com.web.daonila.message.resp.NewsMessage;
import com.web.daonila.util.MessageUtil;
import com.web.model.BookInfo;
import com.web.service.BookService;

//
@Component
public class MeetGoodBookResp extends MessageRespHandler<Article> implements MessageRespBase{
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private BookService bookService;

	public String start(Map<String, String> requestMap) {
		init(requestMap);
		logger.info("TextMessageResp.start():{requestMap={}}", new Object[]{requestMap.toString()});
		return run();
	}

	@Override
	protected String validMessage(Map<String, String> requestMap) {
	    NewsMessage newsMessage = new NewsMessage();  
        newsMessage.setToUserName(fromUserName);  
        newsMessage.setFromUserName(toUserName);  
        newsMessage.setCreateTime(new Date().getTime());  
        newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS); 
        int max=200;
        int min=0;
        Random random = new Random();

        int s = random.nextInt(max)%(max-min+1) + min;
        newsMessage.setFuncFlag(0);
		BookInfo bookInfo = new BookInfo();
		bookInfo.setStart(s);
		bookInfo.setLimit(s+1);
		List<BookInfo> books = bookService.findBooks(bookInfo);
		if(books.isEmpty()) {
			return "is empty";
		}
		List<Article> articles = new ArrayList<Article>();
		for (BookInfo book : books) {
			Article article = new Article();
			article.setTitle(book.getBookName());
			article.setDescription(book.getBookDesc());
			articles.add(article);
		}
		newsMessage.setArticleCount(articles.size());
		newsMessage.setArticles(articles);
		return MessageUtil.newsMessageToXml(newsMessage);
	}

}
